package com.ostrich.demomvvm.net

import androidx.lifecycle.LiveData
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Callback
import retrofit2.Response
import java.lang.reflect.Type
import java.util.concurrent.atomic.AtomicBoolean

/**
 * @Author : yaotianxue
 * @Time : On 2023/10/18 16:08
 * @Description : LiveDataCallAdapter
 */
class LiveDataCallAdapter<T>(private val type:Type):CallAdapter<T,LiveData<T>> {
    override fun responseType(): Type {
        return type
    }

    override fun adapt(call: Call<T>): LiveData<T> {

        return object : LiveData<T>(){
            //确保多线程情况下安全的运行，不会被其他线程打断，一直等到该方法执行完成，才由jvm从等待队列中选择其他线程进入
            private var started = AtomicBoolean(false)
            override fun onActive() {
                super.onActive()
                if(started.compareAndSet(false,true)){
                    call.enqueue(object : Callback<T>{
                        override fun onResponse(call: Call<T>, response: Response<T>) {
                            if(response.code() == 200){
                                postValue(response.body())
                            }else{
                                postValue(BaseResponse(response.code(),"",response.message()) as T)
                            }
                        }

                        override fun onFailure(call: Call<T>, t: Throwable) {
                            postValue(BaseResponse(404,"",t.message.toString()) as T)
                        }

                    })
                }
            }
        }


    }
}